<template>
  <view class="container">
    <view
      class="flex benben-position-layout flex flex-wrap align-center list_flex_0_ibhf"
      :style="{ height: 88 + StatusBarRpx + 'rpx', paddingTop: StatusBarRpx + 'rpx' }"
    >
      <view class="flex flex-wrap align-center justify-between flex-sub list_fd0_0_ibhf">
        <view class="flex flex-wrap align-center list_fd0_0_c0_ibhf" @tap.stop="handleJumpDiy" data-type="back" data-url="1">
          <text class="fu-iconfont2 list_fd0_0_c0_c0_ibhf">&#xE794;</text>
        </view>
        <view class="flex flex-wrap align-stretch justify-center">
          <text class="list_fd0_0_c1_c0_ibhf">课程章节</text>
        </view>
        <view class="flex flex-wrap align-center justify-end list_fd0_0_c0_ibhf"></view>
      </view>
    </view>
    <view :style="{ height: 88 + StatusBarRpx + 'rpx' }"></view>
    <!-- 章节列表 -->
    <scroll-view class="chapter-list" scroll-y>
      <!-- 递归渲染章节树 -->
      <chapter-node
        v-for="chapter in chapterTree"
        :key="chapter.id"
        :node="chapter"
        :level="0"
        @on-edit="handleEdit"
        @on-jump="jumpurl"
        @on-add-child="handleAddChild"
        @on-delete="handleDelete"
        @on-click="addml"
      />

      <!-- 新增一级目录按钮 -->
      <view :style="{ height: '88rpx' }"></view>
      <view class="flex flex-wrap align-center justify-center benben-position-layout flex list_flex_2_ibhf">
        <button class="list_fd2_0_ibhf" @tap.stop="add(0, 0, 0)">新增一级目录</button>
      </view>
      <!-- <view class="add-root-btn" @click="showAddRootDialog">
				<text class="add-icon">+</text>
				<text class="add-text">新增一级目录</text>
			</view> -->
    </scroll-view>

    <!-- 操作弹窗 -->
    <benben-popup
      v-model="popupShow1758159673073"
      :mask="true"
      :mask-close-able="true"
      mode="center"
      :z-index="9999"
      background-color="rgba(0, 0, 0, 0.5)"
    >
      <!---flex布局2flex布局开始-->
      <view class="flex flex-wrap align-center justify-center benben-flex-layout people_flex_3_ibhf">
        <view class="flex flex-direction align-center people_fd3_0_ibhf">
          <view class="flex flex-direction align-center justify-center people_fd3_0_c0_ibhf">
            <text class="people_fd3_0_c0_c0_ibhf">{{ title }}</text>
          </view>
          <view class="flex flex-wrap align-center people_fd3_0_c1_ibhf">
            <benben-input
              class="flex-sub people_fd3_0_c1_c0_ibhf"
              type="text"
              :placeholder="inputname"
              confirm-type="done"
              :maxlength="-1"
              :adjust-position="true"
              v-model="inputone"
              placeholder-style="color:rgba(153, 153, 153, 1);font-size:28rpx"
            />
          </view>
          <view class="flex flex-wrap align-center people_fd3_0_c1_ibhf">
            <benben-input
              class="flex-sub people_fd3_0_c1_c0_ibhf"
              type="text"
              :placeholder="inputsort"
              confirm-type="done"
              :maxlength="-1"
              :adjust-position="true"
              v-model="inputtwo"
              placeholder-style="color:rgba(153, 153, 153, 1);font-size:28rpx"
            />
          </view>
          <view class="flex flex-wrap align-center people_fd3_0_c3_ibhf">
            <view class="flex flex-wrap align-center justify-center people_fd3_0_c3_c0_ibhf" @tap.stop="popupShow1758159673073 = false">
              <text>取消</text>
            </view>
            <view class="flex flex-wrap align-center justify-center people_fd3_0_c3_c1_ibhf" @tap.stop="tj">
              <text>提交</text>
            </view>
          </view>
        </view>
      </view>
    </benben-popup>
    <benben-popup v-model="iseditopen" :mask="true" :mask-close-able="true" mode="center" :z-index="9999" background-color="rgba(0, 0, 0, 0.5)">
      <!---flex布局2flex布局开始-->
      <view class="flex flex-wrap align-center justify-center benben-flex-layout people_flex_3_ibhf">
        <view class="flex flex-direction align-center people_fd3_0_ibhf">
          <view class="flex flex-direction align-center justify-center people_fd3_0_c0_ibhf">
            <text class="people_fd3_0_c0_c0_ibhf">修改章节名称</text>
          </view>
          <view class="flex flex-wrap align-center people_fd3_0_c1_ibhf" style="margin-bottom: 100rpx">
            <benben-input
              class="flex-sub people_fd3_0_c1_c0_ibhf"
              type="text"
              placeholder="请输入章节名称"
              confirm-type="done"
              :maxlength="-1"
              :adjust-position="true"
              v-model="inputzjmc"
              placeholder-style="color:rgba(153, 153, 153, 1);font-size:28rpx"
            />
          </view>
          <!-- <view class='flex flex-wrap align-center people_fd3_0_c1_ibhf'>
						<benben-input class='flex-sub people_fd3_0_c1_c0_ibhf' type="text" :placeholder="inputsort"
							confirm-type="done" :maxlength="-1" :adjust-position='true' v-model="inputtwo"
							placeholder-style="color:rgba(153, 153, 153, 1);font-size:28rpx" />
					</view> -->
          <view class="flex flex-wrap align-center people_fd3_0_c3_ibhf">
            <view class="flex flex-wrap align-center justify-center people_fd3_0_c3_c0_ibhf" @tap.stop="iseditopen = false">
              <text>取消</text>
            </view>
            <view class="flex flex-wrap align-center justify-center people_fd3_0_c3_c1_ibhf" @tap.stop="tjedit">
              <text>提交</text>
            </view>
          </view>
        </view>
      </view>

      <!---flex布局2flex布局结束-->
    </benben-popup>

    <!-- <chapter-dialog :show="showDialog" :type="dialogType" :current-node="currentNode" @confirm="handleDialogConfirm"
			@cancel="handleDialogCancel" /> -->
  </view>
</template>

<script>
import ChapterNode from './node.vue'
import ChapterDialog from './dialog.vue'
import { encryptWeb } from '@/common/utils/crypto.js'
import { host, API_VERSION } from '@/common/config.js'

export default {
  components: {
    ChapterNode,
    ChapterDialog,
  },
  data() {
    return {
      showDialog: false,
      dialogType: 'addRoot', // addRoot, edit, addChild
      currentNode: null,
      chapterTree: [],
      course: '', //课程id
      bookid: '', //素材id
      popupShow1758159673073: false,
      iseditopen: false, //重命名弹框
      inputzjmc: '', //
      /** isopen【是否显示二级】
       *   isopen【是否显示三级】
       *   isopen【是否显示三级】
       *   isopen【是否显示二级】 **/
      course: '', //课程id
      list: [],
      title: '新增一级目录', //弹框标题
      inputname: '请输入一级目录名称，必填项', //输入框占位符
      inputone: '', //输入框绑值
      inputsort: '排序，正整数', //输入框占位符
      inputtwo: '', //输入框绑值
      chapter_id: '', //章节id
      opencb: false,
    }
  },
  onLoad(options) {
    this.course = options.course
    this.bookid = options.bookid
    this.getlist()
  },
  methods: {
    async getlist() {
      let res = await this.$api.post(global.apiUrls.post6818697f95795, {
        course_id: this.course,
      })

      if (res.data.code == 1) {
        console.log(res.data)
        this.chapterTree = res.data.data.list
        console.log(this.chapterTree)
        // this.$emit('myEvent', res.data.data.num);
      }
    },
    addml(node) {
      this.currentNode = node
      this.add(1)
    },
    add(type, item, index) {
      console.log(type)
      this.popupShow1758159673073 = true
      this.inputone = ''
      this.inputtwo = ''
      if (type == 0) {
        this.chapter_id = '0'
        this.title = '新增一级目录'
        this.inputname = '请输入一级目录名称，必填项'
        this.inputsort = '排序，正整数'
      } else {
        this.chapter_id = this.currentNode.aid
        this.title = '新增目录'
        this.inputname = '请输入目录名称，必填项'
        this.inputsort = '排序，正整数'
      }
      // console.log(this.currentNode.aid)
      // console.log(this.currentNode.name)
    },
    // 提交新增子章节
    async tj() {
      if (!this.inputone) {
        this.$message.info(this.inputname)
        return
      }
      if (!this.inputtwo) {
        this.$message.info('请输入排序')
        return
      }
      let obj = {
        name: this.inputone,
        textbook_id: this.bookid,
        chapter_id: this.chapter_id,
        sort: this.inputtwo,
        course_id: this.course,
      }
      console.log(obj)
      // return

      let res = await this.$api.post(global.apiUrls.post67f729fb09adc, obj)
      if (res.data.code != 1) {
        this.$message.info(res.data.msg)
        return
      }
      console.log(res.data.data)
      this.popupShow1758159673073 = false
      this.getlist()
    },
    // 处理编辑
    handleEdit(node) {
      this.dialogType = 'edit'
      this.currentNode = node
      console.log(node)
      this.edit()
      // this.showDialog = true
    },
    // 跳转资源
    jumpurl(node) {
      if (node.level <= 1) return
      let params = {
        cid: this.bookid,
        chaperid: node.aid,
        StatusBar: this.StatusBar,
        // playScene: 'study',
        playScene: 'preview',
        token: this.$store.state.token,
        api: host,
        mid: API_VERSION.replace('m', ''),
      }
      let path = `https://dev.gj.teacher.zhongbenjiaoyu.cn/video-business/chapter-preview?params=${encodeURIComponent(
        encryptWeb(JSON.stringify(params))
      )}`
      // let path = `http://localhost:5173/video-business/chapter-preview?params=${encodeURIComponent(encryptWeb(JSON.stringify(params)))}`
      uni.setStorageSync('zhongbenjiaoyuPath', path)
      uni.navigateTo({ url: `/pages/benben-built-in/web-view/web-view?params=1` })
    },
    // 重命名
    async tjedit() {
      if (!this.inputzjmc) {
        this.$message.info('请输入章节名称')
        return
      }
      let obj = {
        name: this.inputzjmc,
        aid: this.chapter_id,
      }
      let res = await this.$api.post(global.apiUrls.post678b4b048051b, obj)
      if (res.data.code != 1) {
        this.$message.info(res.data.msg)
        return
      }
      console.log(res.data.data)
      this.iseditopen = false
      this.getlist()
    },

    edit(type, item, index) {
      this.iseditopen = true
      this.inputzjmc = this.currentNode.name
      this.chapter_id = this.currentNode.aid
    },
    // 显示新增一级目录弹窗
    // showAddRootDialog() {
    // 	this.dialogType = 'addRoot'
    // 	this.currentNode = null
    // 	this.showDialog = true
    // },

    // 处理新增子集
    handleAddChild(node) {
      this.dialogType = 'addChild'
      this.currentNode = node
      this.showDialog = true
    },

    // 处理删除
    handleDelete(node) {
      this.chapter_id = node.aid
      uni.showModal({
        title: '确认删除',
        content: `确定要删除 "${node.name}" 吗？此操作不可恢复。`,
        confirmColor: '#e74c3c',
        success: (res) => {
          if (res.confirm) {
            this.delzj(this.chapterTree, node.id)
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })
          }
        },
      })
    },
    // 删除章节
    async delzj() {
      let res = await this.$api.post(global.apiUrls.post68ccd30915bac, {
        aid: this.chapter_id,
      })
      if (res.data.code != 1) {
        this.$message.info(res.data.msg)
        return
      }
      console.log(res.data.data)
      // this.iseditopen=false
      this.getlist()
    },

    // 递归删除节点
    deleteNode(nodes, id) {
      const index = nodes.findIndex((node) => node.id === id)
      if (index > -1) {
        nodes.splice(index, 1)
        return true
      }

      for (let node of nodes) {
        if (node.children && this.deleteNode(node.children, id)) {
          return true
        }
      }
      return false
    },

    // // 处理弹窗确认
    // handleDialogConfirm(data) {
    // 	const {
    // 		title
    // 	} = data

    // 	switch (this.dialogType) {
    // 		case 'addRoot':
    // 			this.addRootChapter(title)
    // 			break
    // 		case 'edit':
    // 			this.editNode(this.chapterTree, this.currentNode.id, title)
    // 			break
    // 		case 'addChild':
    // 			this.addChildNode(this.chapterTree, this.currentNode.id, title)
    // 			break
    // 	}

    // 	this.showDialog = false
    // 	this.currentNode = null
    // },

    // 处理弹窗取消
    handleDialogCancel() {
      this.showDialog = false
      this.currentNode = null
    },

    // 添加根章节
    addRootChapter(title) {
      const newChapter = {
        id: Date.now().toString(),
        title: title,
        children: [],
      }
      this.chapterTree.push(newChapter)
    },

    // 编辑节点
    editNode(nodes, id, title) {
      for (let node of nodes) {
        if (node.id === id) {
          node.title = title
          return true
        }
        if (node.children && this.editNode(node.children, id, title)) {
          return true
        }
      }
      return false
    },

    // 添加子节点
    addChildNode(nodes, parentId, title) {
      for (let node of nodes) {
        if (node.id === parentId) {
          if (!node.children) {
            node.children = []
          }
          const childCount = node.children.length + 1
          node.children.push({
            id: `${parentId}.${childCount}`,
            title: title,
            children: [],
          })
          return true
        }
        if (node.children && this.addChildNode(node.children, parentId, title)) {
          return true
        }
      }
      return false
    },
  },
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  background: #ffffff;
}

.header {
  padding: 40rpx 30rpx 30rpx;
  background: white;
  border-bottom: 1rpx solid #e0e0e0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.chapter-list {
  height: calc(100vh - 160rpx);
  /* padding: 0 24rpx; */
}

.add-root-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  margin: 20rpx 0;
  background: white;
  border: 2rpx dashed #dcdfe6;
  border-radius: 12rpx;
  color: #909399;
}

.add-icon {
  font-size: 32rpx;
  margin-right: 15rpx;
  font-weight: bold;
}

.add-text {
  font-size: 28rpx;
}

.list_flex_0_ibhf {
  width: 750rpx;
  height: 88rpx;
  overflow: hidden;
  z-index: 10;
  top: 0rpx;
  background: #fff;
  background-size: 100% auto !important;

  .list_fd0_0_ibhf {
    padding: 0rpx 32rpx 0rpx 32rpx;

    .list_fd0_0_c1_c0_ibhf {
      font-size: 36rpx;
      font-weight: 700;
      color: #333333;
      line-height: 50rpx;
    }
  }
}
.list_flex_2_ibhf {
  width: 750rpx;
  height: 88rpx;
  overflow: hidden;
  z-index: 10;
  bottom: calc(88rpx + var(--window-bottom));

  .list_fd2_0_ibhf {
    border-radius: 33rpx 33rpx 33rpx 33rpx;
    width: 80%;
    line-height: 88rpx;
    font-size: 24rpx;
    background: #4781f5;
    color: #fff;
  }
}
.people_flex_3_ibhf {
  width: 622rpx;
  margin: 0rpx 0rpx 0rpx 64rpx;

  .people_fd3_0_ibhf {
    background: #ffffff;
    width: 622rpx;
    height: 530rpx;
    border-radius: 16rpx;

    .people_fd3_0_c0_ibhf {
      margin: 48rpx 0rpx 48rpx 0rpx;

      .people_fd3_0_c0_c0_ibhf {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .people_fd3_0_c3_ibhf {
      color: var(--benbenFontColor3);
      font-size: 32rpx;

      .people_fd3_0_c3_c0_ibhf {
        background: #f4f8fd;
        width: 240rpx;
        height: 88rpx;
        margin: 0rpx 44rpx 0rpx 0rpx;
        border-radius: 44rpx;
        color: rgba(20, 94, 253, 1);
        font-size: 32rpx;
      }

      .people_fd3_0_c3_c1_ibhf {
        background: #145efd;
        width: 240rpx;
        height: 88rpx;
        border-radius: 44rpx;
        color: #fff;
      }
    }

    .people_fd3_0_c1_ibhf {
      border: 1px solid #f2f4f7;
      background: #f6f7fa;
      width: 526rpx;
      height: 84rpx;
      margin: 0rpx 0rpx 24rpx 0rpx;
      border-radius: 12rpx;
      padding: 0 24rpx;
    }
  }
}
</style>
